using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using System.Xml;

namespace OrbitOne.CRMUpdater.CRM
{
    public class Connection
    {
        #region Properties
        public string UserName { get; set; }
        public string Domain { get; set; }
        public string Server { get; set; }
        public string Instance { get; set; }
        public int Authentication { get; set; }
        [XmlIgnore]
        public string Password { get; set; }
        public string EncryptedPassword
        {
            get { return Convert.ToBase64String(Password.Select(c => (byte)c).ToArray()); }
            set { Password = string.Join("", Convert.FromBase64String(value).Select(b => ((char)b).ToString()).ToArray()); }
        }
        public string Label { get; set; } 
        #endregion

        #region Constructors
        public Connection(string label, string username, string password, string domain, string server, string instance, int authentication)
        {
            UserName = username;
            Password = password;
            Domain = domain;
            Server = server;
            Instance = instance;
            Authentication = authentication;
            Label = label;
        }
        public Connection()
        {

        } 
        #endregion

        #region Public static methods
        public static List<Connection> Load()
        {
            try
            {
                var serializer = new XmlSerializer(typeof(List<Connection>));
                var blah = serializer.Deserialize(XmlReader.Create("Connections.xml"));
                return (List<Connection>)blah;
            }
            catch
            {
                return new List<Connection>();
            }
        }
        public static void Save(List<Connection> connections)
        {
            var serializer = new XmlSerializer(typeof(List<Connection>));
            serializer.Serialize(XmlWriter.Create("Connections.xml"), connections);
        } 
        #endregion
    }
}